<?php

/**
 * @category   Ac
 * @package    Application_Model
 * @copyright  Orient Network Ltd
 * @license    Closed
 * @author     Olivier Bregeras
 */
class Model_Company extends Ac_Model
{

    const STATUS_ACTIVE  = 1;
    const STATUS_BANNED  = 2;
    const STATUS_DELETED = 3;

    const TYPE = 9;

    protected static  $_collection = 'company';
	//conngroup for user and company models
	protected static $_connectionGroup = 'accounts';
	//db for user and company
	protected static $_db = SHARED_ACCOUNTS_ENV;
    /**
     *
     * @var array define the requirements for this model
     */
    protected static $_requirements = array(
        //'un'  => array('Required', 'Validator:EmailAddress'), //Email
        'ph' => array('Array'), //Photo
    );

    protected static $_transcript = array(
        '_id' => '_id',
        'un' => 'username',
        'em' => 'email',
        'cn' => 'company_name',
        'ma' => 'mailing_address',
        'im' => 'image',
        'ph' => 'phone',
        'ws' => 'website',
        'we' => 'weibo',
        'bc' => 'business_category',
        'ne' => 'number_employees',
        'fa' => 'fax',
        'lo' => 'location',
        'ft' => 'facebook_twitter',
        'bl' => 'backlink',
        'ab' => 'about',
        'ctn' => 'contact_name',
        'cj' => 'contact_job',
        'cd' => 'contact_department',
        'cp' => 'contact_phone',
        'ce' => 'contact_email',
        'cm' => 'contact_messenger',
        'la' => 'latitude',
        'lg' => 'longitude',
        'st' => 'status',
        'nv' => 'number_views',
        'c_dt' => 'created_at',
        'pho' => 'photos',
        'phc' => 'photos_count',
        'fpi'   => 'featured_photo_id',
        'cli' => 'count_likes',
        'cfe' => 'count_followers',
        'cfi' => 'count_following'        
   );

    public function __construct($data = array(), $config = array())
	{
        $config['collection'] = 'company';
        self::ensureIndex(array('c_dt'));
        parent::__construct($data, $config);
    }

	public function __isset($name) {
        $val = self::__get($name);
        return!empty($val) ? true : parent::__isset($name);
    }

	public function deleteCompany()
	{
		$this->status = self::STATUS_DELETED;
		$this->save();
        $this->postSave();
	}
	
    public function postSave()
    {
        $doc = $this->getSolrDocument();
        if ($doc !== false) {
            $client = Ac_Search::getClient();
            $client->addDocument($doc);
            $client->commit();
        }
    }

    public function url($full_url = false, $params = array())
    {
        $view = Zend_Registry::get('Zend_View');
        return ($full_url ? 'http://'.$_SERVER['SERVER_NAME'].'':'') . $view->geturl('display-company', 'user', array('company' => $this), 'company1', $params);        
    }

    public function getSolrDocument()
    {
        $document = new Apache_Solr_Document();
        $document->id = (string) $this->_id; //or something else suitably unique
        $document->type_obj = self::TYPE;
        $document->type_obj_s = 'Model_Company';
        // $document->status   = (empty($this->status) || $this->status == self::STATUS_ACTIVE) ? self::STATUS_ACTIVE : self::STATUS_DELETED;
		$document->status     = (empty($this->status) || $this->status == self::STATUS_ACTIVE)? self::STATUS_ACTIVE : (($this->status == self::STATUS_BANNED)?self::STATUS_BANNED : self::STATUS_DELETED);

/*
        foreach ((array) $this->business_category as $cat) {
            $cat = Model_Category::find($cat);
            foreach((array)$cat->path as $id) {
                $document->addField('category', (string)$id);
                $document->addField('category_l1', (string)$id);
                $catid = Model_Category::find($id);
                // if (!empty($catid)) {
                    // $document->addField('category_name', (string)$catid->nm_en);
                    // $document->addField('category_name', (string)$catid->nm_tc);
                // }
            }
        }
        */

        if (!empty($this->bc)) {
            foreach ((array)$this->bc as $id) {
                $cat = Model_Category::find($id);
                $document->addField('category', BUSINESS_DIRECTORY_CATEGORY);
                $document->addField('category_l1', BUSINESS_DIRECTORY_CATEGORY);
                if (!empty($cat)) {
                    $document->addField('category_attached', (string)$cat->_id);
                    $document->addField('category_l2', (string)$cat->_id);
                }
            }
        }

        if (!empty($this->lo)) {
            $loc = Model_Location::find($this->lo);
            if (!empty($loc)) {
                $document->area_l2 = (string)$this->lo;
                $document->area_l1 = (string)$loc->path[0];;
            }
        }

        $document->company_id       = (string)$this->id;
        $document->company_name     = (string)$this->nm;
        //$document->addField('about', (string)$this->ab);
        $document->username         = (string)$this->un;
        $document->photo            = (string)$this->im;
        $document->url              = $this->url();
        if (!is_object($this->c_dt)) {
            $document->created_at       = gmdate ('Y-m-d\TH:i:s\Z', strtotime($this->c_dt));
        } else {
            $document->created_at       = gmdate ('Y-m-d\TH:i:s\Z', $this->c_dt->sec);
        }

        return $document;
    }
    
    public function preSave()
    {
        if (empty($this->c_dt)) {
            $this->c_dt = new MongoDate(time());
        }
        if (!is_object($this->c_dt)) {
            $this->c_dt = new MongoDate($this->c_dt);
        }
        if (empty($this->st)) {
            $this->st = self::STATUS_ACTIVE;
        } 
    }

    /**
     * We use Map/Reduce do to calculation on the number of views
     * @return int
     */
    public function getNoViews()
    {
        /*
        $users = array();
        $list = Model_User::all(array('cid' => $this->_id));
        foreach($list as $user) {
            $users[] = $user->_id;
        }

        $map = new MongoCode('function() { emit(this.user_id, this.nv); }');
        $reduce = new MongoCode('function(k, vals) { '.
            'var sum = 0;'.
            'for (var i in vals) {'.
                'sum += vals[i];'.
            '}'.
            'return sum; }');

        $sales = self::getMongoDb()->command(array(
            'mapreduce' => 'listing',
            'map'       => $map,
            'reduce'    => $reduce,
            'query'     => array('us' => array('$in' =>  $users), 'sa' => Model_Listing::STATUS_PUBLISHED)));

        $views = self::getMongoDb()->selectCollection($sales['result'])->findOne();
        return $views['value'];
        */
        return $this->number_views;
    }

    public static function getBusinessCategory()
    {
        $bd = Model_Category::one(array('id' => 'mc52'));
        $id = $bd->_id;

//        $locs = Model_Category::all(array('_id' => array('$ne' => new MongoId($id)),  'path' => new MongoId($id), 'status' => Model_Category::STATUS_ACTIVE))->sort(array('pos' => 1));
        $locs = Model_Category::all(array('_id' => array('$ne' => $id),  'path' => $id, 'status' => Model_Category::STATUS_ACTIVE))->sort(array('pos' => 1));
        $parent = '';
        $locations=array();
        $locations[''] = 'Select';
        foreach($locs as $k => $loc) {
 //           if (count($loc->path) == 2) {
                 $locations[(string)$loc->_id] =  $loc->name;
 //           } 
        }
        return $locations;
    }

    public function __get($name)
    {
        if ($name == 'location') {
            $id = parent::__get('location');
            $res = Model_Location::find($id);
            return $res;
        } elseif ($name == 'area_l1') {
            $loc = self::__get('area_l2');
            if (!empty($loc)) {
                return $loc->getParent();
            }
        } elseif ($name == 'area_l2') {
            $id = parent::__get('location');
            $res = Model_Location::find($id);
            return $res;
        } else if($name == 'featured_photo') {
            return $this->pho[$this->featured_photo_id];            
        } else {
            return parent::__get($name);
        }
    }

    public function __call($name, $arguments)
    {
        if($name == 'followers') {
            $limit = empty($arguments['limit']) ? 10 : $arguments['limit'];
            $list   = Model_Follow::getFollowers($this->_id)->limit($limit);
            return $list;
        } elseif($name == 'following') {
            $limit = empty($arguments['limit']) ? 10 : $arguments['limit'];
            $list   = Model_Follow::getFollowing($this->_id)->limit($limit);
            return $list;
        } else {
            return parent::_call($name, $arguments);
        }
    }


    public function getUser()
    {
        return Model_User::one(array('cid'=>$this->_id));
    }

    public static function getSearchResultPartialName()
    {
        return 'company';
    }    
}
